﻿@{
    ViewBag.Title = "品牌列表";
}
@section Header{

    <link href="~/Content/assets/css/bootstrapValidator.css" rel="stylesheet" />
    <link href="~/Content/Plug/cropbox/css/style.css" rel="stylesheet" />
    @*表单验证样式*@
    <style type="text/css">
        .has-feedback .form-control-feedback {
            position: absolute;
            top: 25px;
            right: 0;
            display: block;
            width: 34px;
            height: 34px;
            line-height: 34px;
            text-align: center;
        }

        .form-horizontal .has-feedback .form-control-feedback {
            top: 0;
            right: 15px;
        }
    </style>
}
<div class="main-content">
    <div class="breadcrumbs" id="breadcrumbs">
        <script type="text/javascript">
            try { ace.settings.check('breadcrumbs', 'fixed') } catch (e) { }
        </script>

        <ul class="breadcrumb">
            <li>
                <i class="icon-home home-icon"></i>
                <a href="/Admin/Home">首页</a>
            </li>
            <li>
                <a href="/Admin/Brand/BrandList">品牌列表</a>
            </li>
            <li class="active">品牌列表</li>
        </ul><!-- .breadcrumb -->
        <!-- #nav-search -->
    </div>
    <div class="page-content">
        <div class="row">
            <div class="col-xs-12">
                <!-- PAGE CONTENT BEGINS -->

                <div class="row">
                    <div class="col-xs-12">
                        <div class="table-header">
                            品牌列表查看
                        </div>
                        <div class="hidden" id="hidden_filter">
                            @* 把需要搜索的条件放到hidden里面，在table格式化完成的时候直接调用$.html()赋值，免去了在js拼接标签的麻烦 *@
                            <label>
                                @Html.TextBox("brandName", "", new { @class = "form-control input-small", style = "width:150px", placeholder = "请输入品牌名称" })
                            </label>
                            <label>
                                <a href="javascript:Search();" class="btn btn-xs btn-primary">
                                    搜索
                                </a>
                                <i class="fa fa-search"></i>
                            </label>
                        </div>
                        <div class="table-responsive dataTables_wrapper">
                            <table id="sample-table-2" class="table table-striped table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th class="center sorting_disabled" role="columnheader" rowspan="1" colspan="1" aria-label="" style="width: 58px;">
                                            <label>
                                                <input type="checkbox" class="ace">
                                                <span class="lbl"></span>
                                            </label>
                                        </th>
                                        <th>品牌缩略图</th>
                                        <th class="hidden-480">品牌名称</th>
                                        <th>品牌简介</th>
                                        <th> 排序顺序</th>
                                        <th>是否推荐到首页</th>
                                        <th>是否显示</th>
                                        <th style="width: 120px;">
                                            <div class="visible-md visible-lg hidden-sm hidden-xs action-buttons">
                                                <a id="AddNewBrand" class="blue" data-toggle="modal" href="" title="添加新品牌">
                                                    <i class="icon-plus-sign bigger-130"></i>
                                                </a>
                                                <a id="DeleteBrands" class="red" href="#" title="批量删除品牌">
                                                    <i class="icon-trash bigger-130"></i>
                                                </a>
                                            </div>
                                        </th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
                <!-- PAGE CONTENT ENDS -->
            </div><!-- /.col -->
        </div><!-- /.row -->
    </div><!-- /.page-content -->
</div><!-- /.main-content -->
<!-- 模态框（Modal） -->
<div class="modal fade" id="ShowAdd" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="main-content col-xs-8" style="margin-top: 70px; margin-left: 15%;">
        <div class="page-content">
            <div class="row">
                <section>
                    <div class="page-header">
                        <h1>
                            品牌管理
                            <small>
                                <i class="icon-double-angle-right"></i>
                                添加品牌
                            </small>
                        </h1>
                    </div>
                    <div class="col-lg-8 col-lg-offset-2">
                        <form id="defaultForm" class="form-horizontal">
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">品牌名称</label>
                                    <div class="col-lg-5" style="float:left;">
                                        <input type="text" class="form-control" name="BrandName" id="BrandName" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">品牌缩略图</label>
                                    <div class="col-lg-5">
                                        <div class="upload">
                                            <div class="imageBox" id="ImgUrlShowDiv">
                                                <div class="thumbBox"></div>
                                                <div class="spinner" style="display: none">Loading...</div>
                                                <input type="hidden" name="Logo" id="Logo" value="" class="CropShowImg" />
                                            </div>
                                            <div class="new-contentarea">
                                                <a href="javascript:void(0)" class="upload-img">
                                                    <label for="upload-file">上传图像</label>
                                                </a>
                                                <input multiple="" type="file" id="LogoImgUpload" name="LogoImgUpload" class="form-control" />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">品牌简介</label>
                                    <div class="col-lg-5">
                                        <input type="text" class="form-control" name="Intro" id="Intro" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">品牌排序</label>
                                    <div class="col-lg-5">
                                        <input type="text" class="form-control" name="OrderNum" id="OrderNum" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">是否显示</label>
                                    <div class="col-lg-5">
                                        <input id="IsShow" type="checkbox" name="IsShow" class="ace ace-switch ace-switch-5 form-control">
                                        <span class="lbl"></span>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">是否推荐到首页</label>
                                    <div class="col-lg-5">
                                        <input id="IsRec" type="checkbox" name="IsRec" class="ace ace-switch ace-switch-5 form-control">
                                        <span class="lbl"></span>
                                    </div>
                                </div>
                            </fieldset>
                            <div class="form-group">
                                <div class="col-lg-9 col-lg-offset-4">
                                    <button class="btn btn-primary" type="submit">
                                        <i class="icon-ok bigger-110"></i>
                                        保存
                                    </button>
                                    <button class="btn" type="reset" data-dismiss="modal">
                                        <i class="icon-undo bigger-110"></i>
                                        取消
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </section>
                <!-- /.row -->
            </div>
        </div>
        <!-- /.page-content -->
    </div>
</div><!-- /.modal -->
@section script{
    <script src="/Content/assets/js/jquery.dataTables.min.js"></script>
    <script src="/Content/assets/js/jquery.dataTables.bootstrap.js"></script>
    <script src="~/Content/assets/js/bootstrapValidator.js"></script>
    <script src="/Content/assets/js/bootbox.min.js"></script>
    <script src="~/Content/Plug/cropbox/js/cropbox.js"></script>
    <script type="text/javascript">
        var isSearch = false;
        $(function () {
            var options =
{
    thumbBox: '.thumbBox',
    spinner: '.spinner',
    imgSrc: '',///Content/Plug/cropbox/images/avatar.png
    cropShowImg: '.CropShowImg'
}
            var cropper = $('.imageBox').cropbox(options);
            $('#LogoImgUpload').on('change', function () {
                var reader = new FileReader();
                reader.onload = function (e) {
                    options.imgSrc = e.target.result;
                    cropper = $('.imageBox').cropbox(options);
                }
                reader.readAsDataURL(this.files[0]);
                this.files = [];
            })


            var objTable = $("#sample-table-2").dataTable({
                aoColumns: [
                    {
                        "sClass": "center", "mDataProp": "Id", "bSortable": false,
                        "fnRender": function (e) {
                            if (e.aData.Id) {
                                return "<label><input type=\"checkbox\" class=\"ace\" value=\"" + e.aData.Id + "\"><span class=\"lbl\"></span></label>";
                            }
                        }
                    },
                    {
                        "sClass": "center", "mDataProp": "Logo", "bSortable": false
                        , "fnRender": function (e) {
                            if (e.aData.Logo) {
                                return " <a href=\"" + e.aData.Logo + "\"><img src=\"" + e.aData.Logo.replace('source', 'thumbS') + "\" alt=\"" + e.aData.Name + " \" width=\"80\" height=\"80\" /></a>";
                            }
                        }
                    },
                     { "sClass": "center", "mDataProp": "Name", "bSortable": false },
                      { "sClass": "center", "mDataProp": "Intro", "bSortable": false },
                    { //自定义列sName
                        "mDataProp": "OrderNum",
                        "sClass": "center",
                        "bSearchable": false,
                        "bSortable": false
                    },
                    {
                        "sClass": "center",
                        "mDataProp": "IsRec",
                        "bSortable": false
                        , "fnRender": function (e) {
                            if (e.aData.IsRec == 1) {
                                return "<i class=\"icon-ok green bigger-120\"></i>";
                            }
                            else {
                                return "<i class=\"icon-remove red bigger-120\"></i>";
                            }
                        }
                    },
                    {
                        "sClass": "center", "mDataProp": "IsShow", "bSortable": false
                        , "fnRender": function (e) {
                            if (e.aData.IsShow == 1) {
                                return "<i class=\"icon-ok green bigger-120\"></i>";
                            }
                            else {
                                return "<i class=\"icon-remove red bigger-120\"></i>";
                            }
                        }
                    },
                    {
                        "sClass": "center",
                        "mDataProp": "Sid",
                        "bSortable": false
                         , "fnRender": function (e) {
                             if (e.aData.Sid) {
                                 var html = "<div class=\"visible-md visible-lg hidden-sm hidden-xs action-buttons\">";
                                 // html += "<a class=\"blue\" href=\"#\"><i class=\"icon-zoom-in bigger-130\"></i></a>";//查看按钮
                                 html += "<a class=\"green\" href=\"javascript:UpdateObj('" + e.aData.Sid + "')\" title=\"编辑\"><i class=\"icon-pencil bigger-130\"></i></a>";//编辑
                                 html += "<a class=\"red\" href=\"javascript:DeleteObj('" + e.aData.Sid + "')\" title=\"删除\"><i class=\"icon-trash bigger-130\"></i></a>";//删除
                                 html += "</div>";
                                 return html;

                             }
                         }
                    }
                ],
                "bServerSide": true,//分页，取数据等等的都放到服务端去
                "bProcessing": true,//载入数据的时候是否显示“载入中”
                "aLengthMenu": [10, 15, 20, 50, 100],
                "iDisplayStart": 0,
                "iDisplayLength": 10,//首次加载的数据条数
                "bStorable": false,//排序操作在服务端进行，所以可以关了。
                "sAjaxSource": "/Admin/Brand/BrandList",
                "fnServerParams": function (aoData) {

                },
                /*如果加上下面这段内容，则使用post方式传递数据*/
                "fnServerData": function (sSource, aoData, fnCallback) {
                    var username = $("#brandName").val();
                    if (!isSearch)
                    { username = ""; }
                    aoData.push({ "name": "BrandName", "value": username });
                    $.ajax({
                        "dataType": 'json',
                        "type": "POST",
                        "url": sSource,
                        "data": aoData,
                        "success": function (resp) {
                            fnCallback(resp); //服务器端返回的对象的returnObject部分是要求的格式
                        }
                    });
                },
                "oLanguage": {
                    "sSearch": "搜索",
                    "sLengthMenu": "每页显示 _MENU_ 条记录",
                    "sZeroRecords": "抱歉， 没有找到",
                    "sInfo": "从 _START_ 到 _END_ 共 _TOTAL_ 条数据",
                    "sInfoEmpty": "没有数据",
                    "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                    "oPaginate": {
                        "sFirst": "首页",
                        "sPrevious": "前一页",
                        "sNext": "后一页",
                        "sLast": "尾页"
                    },
                    "sZeroRecords": "没有检索到数据",
                    "sProcessing": "<img src='/Content/assets/images/loading.gif' />"
                }
            });
            $("#sample-table-2_filter").html("<form id='filter_form'>" + $("#hidden_filter").html() + "</form>");
            $("#hidden_filter").html("");

            //表单验证
            $('#defaultForm').bootstrapValidator({
                message: '输入信息验证未通过',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    BrandName: {
                        message: 'The username is not valid',
                        validators: {
                            notEmpty: {
                                message: '品牌名称不能为空'
                            },
                            stringLength: {
                                min: 1,
                                max: 30,
                                message: '品牌名称长度只能在1-30之间'
                            },
                            //threshold :  2 , //有6字符以上才发送ajax请求，（input中输入一个字符，插件会向服务器发送一次，设置限制，6字符以上才开始）
                            //remote: {//ajax验证。server result:{"valid",true or false} 向服务发送当前input name值，获得一个json数据。例表示正确：{"valid",true}  
                            //    url: '/Admin/Brand/ExistBrand',//验证地址
                            //    message: '品牌名称已存在',//提示消息
                            //    delay: 2000,//每输入一个字符，就发ajax请求，服务器压力还是太大，设置2秒发送一次ajax（默认输入一个字符，提交一次，服务器压力太大）
                            //    type: 'POST'//请求方式
                            //    /**自定义提交数据，默认值提交当前input value
                            //     *  data: function(validator) {
                            //          return {
                            //              password: $('[name="passwordNameAttributeInYourForm"]').val(),
                            //              whatever: $('[name="whateverNameAttributeInYourForm"]').val()
                            //          };
                            //       }
                            //     */
                            //},
                             callback: {
                                message: '品牌名称已存在',
                                callback: function (value, validator) {
                                    $.ajax({
                                        type: "post",
                                        url: "/Admin/Brand/ExistBrand",
                                        data: { "BrandName": value },
                                        dataType: "json",
                                        success: function (res) {
                                            if (res.state == "fail") {
                                                return false;
                                            } else {
                                                return true;
                                            }
                                        }
                                    })
                                    return true;
                                }
                            }
                        }
                    },
                    Intro: {
                        validators: {
                            stringLength: {
                                max: 100,
                                message: '品牌简介长度不能超过100'
                            }
                        }
                    },
                    OrderNum: {
                        validators: {
                            notEmpty: {
                                message: '排序数字不能为空'
                            },
                            greaterthan: {
                                message: '请输入正确的排序数字',
                                inclusive: true,
                                value: 0
                            },
                            lessThan: {
                                value: 10000,
                                inclusive: true,
                                message: '请输入正确的排序数字'
                            }
                        }
                    }
                }
            }).on('success.form.bv', function (e) {
                e.preventDefault();
                var data = [];
                data.push({ "name": "BrandName", "value": $("#BrandName").val() });
                var brandLogo = $("#Logo").val();
                if (brandLogo == "") {
                    bootbox.alert({
                        buttons: {
                            ok: {
                                label: '我知道了！',
                                className: 'btn-primary'
                            }
                        },
                        message: '品牌图片不能为空'
                    });
                    //jQuery.validator.addMethod("ImgUrlShowDiv", false, "品牌图片不能为空");
                }
                if (brandLogo.split(',').length > 1) {
                    brandLogo = cropper.getDataURL().replace('data:image/png;base64,', '');
                }
                data.push({ "name": "Logo", "value": brandLogo });
                data.push({ "name": "Intro", "value": $("#Intro").val().replace(/\r\n/g, "<BR>").replace(/\n/g, "<BR>") });
                data.push({ "name": "OrderNum", "value": $("#OrderNum").val() });
                data.push({ "name": "IsShow", "value": $("#IsShow").is(':checked') ? 1 : 0 });
                data.push({ "name": "IsRec", "value": $("#IsRec").is(':checked') ? 1 : 0 });
                $.ajax({
                    type: "post",
                    url: "/Admin/Brand/AddBrand",
                    dataType: "json",
                    data: data,
                    success: function (res) {
                        if (res.state == "fail") {
                            $('#defaultForm').bootstrapValidator('updatestates', 'BrandName', 'INVALID').bootstrapValidator('validateField', 'BrandName');
                        } else if (res.state == "error") {
                            alert(res.message);
                        } else {
                            $("#sample-table-2").dataTable().fnDraw();//重新绘制table。
                            $("#defaultForm").data('bootstrapValidator').resetForm();
                            $('#ShowAdd').modal('hide');//关闭模态框
                            document.getElementById("defaultForm").reset();//情况表单
                        }
                    }
                })
            });

            $(document).on("submit", "#filter_form", function () {
                return false;
            });
          
            $(document).on("click", ".show-detail-json", function () {//取出当前行的数据
                alert(JSON.stringify($("#table_server").DataTable().row($(this).parents("tr")).data()));
            });
            //单选框全选
            $('table th input:checkbox').on('click', function () {
                var that = this;
                $(this).closest('table').find('tr > td:first-child input:checkbox')
                .each(function () {
                    this.checked = that.checked;
                    $(this).closest('tr').toggleClass('selected');
                });

            });

            //tooltip
            $("#AddNewBrand").tooltip({
                show: {
                    effect: "slideDown",
                    delay: 250
                }
            });
            $("#DeleteBrands").tooltip({
                show: {
                    effect: "slideDown",
                    delay: 250
                }
            });
        })
        //搜索
        function Search() {
            isSearch = true;
            $("#sample-table-2").dataTable().fnDraw();//点搜索重新绘制table。
        }
        $('#IsShow').attr('checked', 'checked').on('click', function () {
            $('#default-buttons .btn').toggleClass('no-border');
        });
        $('#IsRec').attr('checked', 'checked').on('click', function () {
            $('#default-buttons .btn').toggleClass('no-border');
        });

        //展示模态框
        $("#AddNewBrand").on('click', function () {
            $('#ShowAdd').modal();
        })


        //单个修改 展示
        function UpdateObj(id) {
            $.ajax({
                type: "post",
                url: "/Admin/Brand/GetBrandModel",
                data: { Id: id },
                dataType: "json",
                success: function (result) {
                    if (result.state == "success") {
                        $("#BrandName").val(result.Brand.Name);
                        $("#Intro").val(result.Brand.Intro);
                        $("#OrderNum").val(result.Brand.OrderNum);
                        if (result.Brand.IsShow == 1) {
                            $("#IsShow").attr("checked", "checked");
                        } else {
                            $("#IsShow").attr("checked", false)
                        }
                        if (result.Brand.IsRec == 1) {
                            $("#IsRec").attr("checked", "checked");
                        } else {
                            $("#IsRec").attr("checked", false)
                        }
                        //重新绘制上传控件
                        var options = {
                            thumbBox: '.thumbBox',
                            spinner: '.spinner',
                            imgSrc: result.Brand.Logo,
                            cropShowImg: '.CropShowImg'
                        }
                        var cropper = $('.imageBox').cropbox(options);
                        $('#ShowAdd').modal('show');
                    } else {
                        bootbox.alert({
                            buttons: {
                                ok: {
                                    label: '我知道了',
                                    className: 'btn btn-primary'
                                }
                            },
                            message: result.message
                        });
                    }
                }
            })
        }
        //删除
        function DeleteObj(id) {
            bootbox.confirm({
                buttons: {
                    confirm: {
                        label: '确认',
                        className: 'btn btn-primary'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-default'
                    }
                },
                message: '确定要删除吗?',
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: "post",
                            url: "/Admin/Brand/DeleteBrand",
                            dataType: "json",
                            data: { Id: id },
                            success: function (result) {
                                if (result.state == "success") {
                                    bootbox.alert({
                                        buttons: {
                                            ok: {
                                                label: '我知道了',
                                                className: 'btn btn-primary'
                                            }
                                        },
                                        message: result.message
                                    });
                                    $("#sample-table-2").dataTable().fnDraw();//重新绘制table。
                                }
                                else {
                                    bootbox.alert({
                                        buttons: {
                                            ok: {
                                                label: '我知道了',
                                                className: 'btn btn-primary'
                                            }
                                        },
                                        message: result.message
                                    });
                                }
                            }
                        })
                    }
                }
            })
        }
    </script>
}
